//
//  HKBaseWebViewController+JSObjectMethod.m
//  HKUtilities
//
//  Created by 胡锦涛 on 2018/11/14.
//  Copyright © 2018 胡锦涛. All rights reserved.
//

#import "HKBaseWebViewController+JSObjectMethod.h"
#import <QuartzCore/QuartzCore.h>
#import <QuartzCore/CoreAnimation.h>
#import <MobileCoreServices/UTCoreTypes.h>
#import "HKIdentify.h"
#import "HKPrefixHeader.h"

@implementation HKBaseWebViewController (JSObjectMethod)

-(void)getResourceInfo{
    
}

-(void)loginFlag:(NSString *)isReload {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"isReload：%@",isReload);
        self.enter = YES;
        //true 不刷新
        if ([isReload isEqualToString:@"true"]) {
            self.isReload = YES;
        }else{
            self.isReload = NO;
        }
        //[self miguLogin];
    });
}

///通过Link协议跳转
-(void)moreLink:(NSString *)link {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.isPresent) {
            //[XBTool presentViewController:self moreLink:link];
        }else{
            //[XBTool presentViewController:self.navigationController moreLink:link];
        }
        
    });
}

//获取请求头信息
- (NSString *)getHeadParams{
    
    HKIdentify * identify = [HKIdentify sharedInstance];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    if (HK_APPCookie) {
        [dict setValue:HK_APPCookie forKey:@"Cookie"];
    }else{
        [dict setValue:@"" forKey:@"Cookie"];
    }
    [dict setValue: [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] forKey:@"version"];
    [dict setValue:identify.deviceId forKey:@"imei"];
    
    [dict setValue:HKIsIPad ?@"2":@"1" forKey:@"clientType"];
    [dict setValue:@"application/json" forKey:@"Accept"];
    return [dict hk_toJsonString];
}

//关闭
-(void)close{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.isPresent) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    });
}

//二级界面跳转 逻辑
-(void)openUrlByClient:(NSString *)url {
    
    NSLog(@"二级界面跳转 url:%@",url);
    dispatch_async(dispatch_get_main_queue(), ^{
        if (url) {
            if ([url containsString:HK_APP_SCHEME]) {
                //[XBTool presentViewController:self.navigationController moreLink:[XBTool encodeValue:url] isFullUrl:NO];
                return;
            }
            
        }
    });
}

//分享
-(void)shareByClient:(NSString *)shareInfo{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (shareInfo) {
        //NSDictionary *dict = [shareInfo HK_jsonDictionary];
        //NSString *shareUrl = dict[@"url"];
        //NSString *title = dict[@"title"];
        //NSString *description = dict[@"description"];
        //NSString *imageUrl = dict[@"pic"];
            
        //分享组件
            
        }
    });
}

/**
 * web返回按钮
 */
-(void)findHomeWay{
    
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//判断是否登陆
-(void)checkLoginState {
    
    if (self.callbackName.length) {
        [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@('%@');",self.callbackName,[[HKIdentify sharedInstance] userState]?@"true":@"false"] completionHandler:^(id _Nullable a, NSError * _Nullable error) {
            NSLog(@"%@",a);
        }];
    }
    
}

//登录
-(void)login{
    
}

//刷新
-(void)refresh{
    
    [self.loadingView addTo:self.webView];
    [self.webView.configuration.userContentController removeAllUserScripts];
    [self.webView addCookie];
    NSError *error;
    NSString *source = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ios_brige" ofType:@"js"] encoding:NSUTF8StringEncoding error:&error];
    if (source) {
        NSString *replacedStr = [source stringByReplacingOccurrencesOfString:@"$headParams" withString:[self getHeadParams]];
        NSString *loginState;
        if ([[HKIdentify sharedInstance] userState]) {
            loginState = @"true";
        } else {
            loginState = @"false";
        }
        replacedStr = [replacedStr stringByReplacingOccurrencesOfString:@"$loginState" withString:loginState];
        WKUserScript *userScript = [[WKUserScript alloc] initWithSource:replacedStr injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
        [self.webView.configuration.userContentController addUserScript:userScript];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.webView reload];
        });
    } else {
        NSLog(@"load brige js error %@", error.localizedDescription);
    }
}

//获取用户信息
-(void)getUserInfo{
    
    if ([HKIdentify sharedInstance].userState) {
        //XBAccountInfo * accountInfo = [XBAccountInfo sharedInstance];
        //NSMutableDictionary *dict = @{}.mutableCopy;
        //if (accountInfo.token.length) {
        //    [dict setObject:accountInfo.token forKey:@"token"];
        //}
        //[self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@('%@');",self.callbackName,[dict HK_jsonString]] completionHandler:nil];
    }
}

#pragma mark -----loginNoti-----
-(void)loginComplete{
    if (self.enter) {
        self.enter = NO;
        if (!self.isReload) {
            [self refresh];
        }
    }else{
        [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@();",self.callbackName] completionHandler:^(id _Nullable a, NSError * _Nullable error) {
            NSLog(@"%@",error);
        }];
        self.isLogin = YES;
    }
}

-(void)showMessage:(NSString *)message{
    [UIAlertController hk_alertWithTarget:self title:@"温馨提示" message:message confirmTitle:@"确认" handler:^{
    }];
}

static NSString *alertCallBack = nil;
//ConfirmAlert
-(void)confirm:(NSString *)params{
    
    NSDictionary *dict = [params hk_jsonDictionary];
    
    if (dict) {
        NSString *title = dict[@"title"];
        NSString *content = dict[@"content"];
        alertCallBack = dict[@"callback"];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:content preferredStyle:UIAlertControllerStyleAlert];
        HKWeakSelf
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            HKStrongSelf
            [self alertViewClickedButtonAtIndex:1];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            HKStrongSelf
            [self alertViewClickedButtonAtIndex:0];
        }];
        [alert addAction:action];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

-(void)alertViewClickedButtonAtIndex:(NSInteger)buttonIndex{
    
    [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@('%ld');",alertCallBack,(long)buttonIndex] completionHandler:^(id _Nullable json, NSError * _Nullable error) {
        
    }];
    
}
@end
